package com.lry.basic.algorithm.graph;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class AdjMatrix {
    private int V;//顶点数
    private int E;//边数
    private int[][] adj;//邻接矩阵

    public AdjMatrix(String filename){
        File file = new File(filename);
        try(Scanner scanner = new Scanner(file)){
            V = scanner.nextInt();//顶点数
            if(V<=0) throw new RuntimeException("顶点个数必须大于0");
            adj = new int[V][V];
            E = scanner.nextInt();//边数
            if(E<0) throw new RuntimeException("边数不能为负数");
            for(int i=0;i<E;i++){
                int a = scanner.nextInt();
                validateVertex(a);
                int b = scanner.nextInt();
                validateVertex(b);
                //自环边检测
                if(a==b){
                    throw new RuntimeException("简单图不能包含自环边");
                }
                //平行边检测
                if(adj[a][b]==1){
                    throw new RuntimeException("简单图不能包含平行边");
                }
                adj[a][b] = 1;
                adj[b][a] = 1;
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private void validateVertex(int v){
        if(v<0||v>=V){
            throw new RuntimeException("顶点下标溢出");
        }
    }
    public int vertexNum(){
        return V;
    }
    public int edgeNum(){
        return E;
    }
    public boolean hasEdge(int v,int w){
        validateVertex(v);
        validateVertex(w);
        return adj[v][w]==1;
    }

    //邻接顶点
    public List<Integer> adj(int v){
        validateVertex(v);
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<V;i++){
            if(adj[v][i]==1){
                list.add(i);
            }
        }
        return list;
    }

    //度
    public int degree(int v){
        validateVertex(v);
        int degree = 0;
        for(int i=0;i<V;i++){
            if(adj[v][i]==1){
                degree++;
            }
        }
        return degree;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("V = %d,E = %d\n",V,E));
        for(int i=0;i<adj.length;i++){
            for(int j=0;j<adj[0].length;j++){
                sb.append(adj[i][j]+" ");
            }
            sb.append("\n");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        AdjMatrix adjMatrix = new AdjMatrix("graph.txt");
        System.out.println(adjMatrix);
        System.out.println(adjMatrix.degree(6));
    }
}
